import httpClient from 'axios';
import {
    getToken
} from './auth';
import { MessageBox } from 'element-ui';
const settings = require('../config/settings');

const service = httpClient.create({
    baseURL: settings.env=='prod'?settings.baseUrl.production:settings.baseUrl.development,
    timeout: settings.network.timeout,
    headers: {
        'Content-Type': settings.network.contentType
    }
});
service.interceptors.request.use((config) => {
    if (getToken()  ) {
        //如果本地缓存中存在token,那么将每次请求,都携带令牌
        config.headers[settings.network.tokenName] = getToken()
        // 处理刷新token后重新请求的自定义变量
        //config['refresh_token'] = false
    }else {
        window.location.href="/#/Login"
    }

    return config
}, error => {
    Promise.reject(error).then((error) => console.log(error));
});

//响应拦截器
service.interceptors.response.use(res=>{//接口访问成功
    //业务逻辑错误，即页面相应200状态码，但是后端不允许进行的逻辑操作
    if(res.data.code && res.data.code == 200){//如果相应码存在且为00
    }else if (res.data.code && res.data.code == 401){
        MessageBox.confirm( '登录状态已过期,请重新登录', {
            confirmButtonText: '登录',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            window.location.href="/#/Login"
        }).catch(() => {

        });
    }else if (res.data.code && res.data.code == 403){
            MessageBox.confirm("权限不足,请联系管理员!",{
                type: 'warning'
            }).then(() => {

            }).catch(() => {

            });
    }
    return res;
},error => {//接口访问失败

    //压根没有访问到我们的后端接口，所以也就没有data对象
    if(error.response.data.code==504 || error.response.data.code==404){
        console.log('页面被吃了，( ╯□╰ )')
    }
    return;
})

export default service;
